﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using DJ.Clients;
using DJ.Dialog;
using DJ.Third;
using DJ.ZEF.ThirdParty;
using HandyControl.Controls;
using Newtonsoft.Json;
using NSJL.Biz.Background.Client;
using NSJL.Biz.Background.Quartzs;
using NSJL.DAL.DataModel.Entities;
using NSJL.DomainModel.Background.Client;
using NSJL.DomainModel.Background.System;
using NSJL.Framework.Utils;
using NSJL.Plugin.Third.ThirdParty;

namespace DJ
{
    /// <summary>
    /// Client.xaml 的交互逻辑
    /// </summary>
    public partial class Client : System.Windows.Window
    {
        CommBiz biz = new CommBiz();
        private UserInfo user = null;
        string cpu {  get; set; }
        DispatcherTimer timer = new DispatcherTimer();
        public Client()
        {
            InitializeComponent();
            
            ComWindow.Start(this);
            TextLogUtil.Info("启动成功");
            Task.Run(() =>
            {
                try
                {
                    #region 锁板串口开启,只启动一次
                    //var ini = new IniFile("Config/Config.ini");
                    //var portName = ini.readKey("BoxConfig", "portName");
                    //var baudRate = ini.readKey("BoxConfig", "baudRate");

                    DevicesInfo devicesInfo = biz.GetDevicesInfo("锁板").FirstOrDefault();
                    if (devicesInfo != null)
                    {
                        var result = LockManager.GetInstance().Start(devicesInfo.COM, devicesInfo.Baud.ToInt32());
                        if (!result.result)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                MessageDialog.ShowDialog(result.message);
                            });
                        }
                    }
                    biz.GetAdminInfo();
                    #endregion
                }
                catch (Exception e)
                {
                    biz.AddFailInfo(e.Message);
                }
            });

            cpu = SelfUtil.GetCPUSerialNumber();
            //刷新授权
            timer.Interval = new TimeSpan(0, 1, 0);
            timer.Tick += ((a, b) =>
            {
                AuthenticationInfo auth = biz.GetAuthInfo(cpu).FirstOrDefault();
                if (auth == null)
                {
                    Dispatcher.Invoke(() =>
                    {
                        AuthExpiresView authExpiresView = new AuthExpiresView();
                        this.Hide();
                        timer.Stop();
                        if (authExpiresView.ShowDialog() == true)
                        {
                            this.Show();
                            timer.Start();
                        }
                    });
                }
                else
                {
                    if (auth.c <= 0 || auth.e <= DateTime.Now)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            AuthExpiresView authExpiresView = new AuthExpiresView();
                            this.Hide();
                            timer.Stop();
                            if (authExpiresView.ShowDialog() == true)
                            {
                                this.Show();
                                timer.Start();
                            }

                        });
                    }
                }
            });
            timer.IsEnabled = true;
            timer.Start();
        }







        private void lab_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                Login login = new Login();
                login.ShowDialog();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
            timer.Stop();
        }

        //存物
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            RssIn:
            BoxTypeView boxTypeView = new BoxTypeView();
            if (boxTypeView.ShowDialog() != true)
            {
                return;
            }
            string boxType = boxTypeView.type;
            BoxInfo box = biz.GetBoxListWithType(boxType);
            AuthInfoView authInfoView = new AuthInfoView();
            if (authInfoView.ShowDialog() != true)
            {
                return;
            }
            var card = authInfoView.card;
            var qrCode = authInfoView.QrCode;
            string code = null;
            string userName = null;
            if (!string.IsNullOrEmpty(qrCode))
            {
                if (biz.GetBoxListWithQrCode(qrCode))
                {
                    MessageDialog.ShowDialog("当前编码已存物");
                    return;
                }
                code = qrCode;
                userName = "扫码";
            }
            if (!string.IsNullOrEmpty(card))
            {
                if (biz.GetBoxListWithUserId(card))
                {
                    MessageDialog.ShowDialog("当前卡号已存物");
                    return;
                }
                code = card;
                userName = "刷卡";
            }
            if (box == null)
            {
                MessageDialog.ShowDialog($"没有空闲{boxType}箱门，请联系管理员");
                VoiceHelper.GetInstance().Start($"没有空闲{boxType}箱门，请联系管理员");
                return;
            }
            //开箱
            LockManager.GetInstance().OpenBox(box.BoxNum);
            SuccessTipView success = new SuccessTipView(box.BoxNum);
            success.ShowDialog();
            biz.EditBoxInfo(box.BoxNum,false, card, code);
            biz.AddOpenBoxInfo(box.BoxNum,userName,code);
            ContinueView con = new ContinueView();
            if (con.ShowDialog() == true)
            {
                goto RssIn;
            }
        }


        //取物
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            AuthInfoView authInfoView = new AuthInfoView();
            if (authInfoView.ShowDialog() != true)
            {
                return;
            }
            var card = authInfoView.card;
            var qrCode = authInfoView.QrCode;
            string code = null;
            string userName = null;
            int boxNum = 0;
            if (!string.IsNullOrEmpty(qrCode))
            {
                code = qrCode;
                userName = "扫码";
                boxNum = biz.GetBoxNumWithQrCode(code);
            }
            if (!string.IsNullOrEmpty(card))
            {
                code = card;
                userName = "刷卡";
                boxNum = biz.GetBoxNumWithUserId(card);
            }
            if (boxNum <= 0)
            {
                MessageDialog.ShowDialog("未查询到箱门");
                return;
            }
            //开箱
            LockManager.GetInstance().OpenBox(boxNum);
            SuccessTipView success = new SuccessTipView(boxNum);
            success.ShowDialog();
            biz.EditBoxInfo(boxNum, true, null, null);
            biz.AddOpenBoxInfo(boxNum, userName, code,true);
        }
    }
}
